//
//  JAddImageCV.m
//  
//  jhf
//
//  Created by 计海峰 on 2017/6/1.
//  Copyright © 2017年 计海峰. All rights reserved.
//

#import "JAddImageCV.h"
#import "TZImageTool.h"
#import <ReactiveObjC/ReactiveObjC.h>
#import <TZImagePreviewController/TZImagePreviewController.h>

@interface JAddImageCV ()

@end

@implementation JAddImageCV

- (void)configDefault; {
    //此处给其增加长按手势，用此手势触发cell移动效果
    UILongPressGestureRecognizer *longGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handlelongGesture:)];
    longGesture.minimumPressDuration = 0.2f; // 触发长按事件时间为：秒
    [self addGestureRecognizer:longGesture];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    JAddImageModel *imageModel = [self.dataArray safeObjectAtIndex:indexPath.row];
    if (!imageModel) {
        return;
    }
    //    jWeakself;
    @weakify(self);
    //是点击了添加按钮
    if (imageModel.isAddBtn) { // 点击了添加按钮
        if (self.dataArray.count > _maxNum) {
            EHUD(@"已经选满了!");
            return;
        }
        if (self.addImageBlock && self.addImageSelfDeal) {
            NSInteger leftImageNum = _maxNum - self.dataArray.count + 1;
            self.addImageBlock(-1, IntToSting(leftImageNum));
            return;
        }
        if (_maxNum != 0) {
            [TZImageTool addPhotosMaxNum:_maxNum - self.dataArray.count + 1 selectedAssets:@[].mutableCopy andTarget:[JUtil findViewController:self] andBlock:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                @strongify(self);
                [self addImages:photos assets:assets];
            }];
        }else{
            [TZImageTool addPhotosMaxNum:_maxNum - self.dataArray.count + 1 selectedAssets:@[].mutableCopy andTarget:[JUtil findViewController:self] andBlock:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto)  {
                @strongify(self);
                [self addImages:photos assets:assets];
            }];
        }
        return;
    }
    if (self.deleteImage) {  // 有删除按钮
        // 没有点击删除按钮 表示预览
        NSMutableArray *array = [NSMutableArray array];
        [self.dataArray enumerateObjectsUsingBlock:^(JAddImageModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
            if (model.imageSource) {
                [array addObject:model.imageSource];
            }
            if (model.imageUrl) {
                [array addObject:cp_imageUrl(model.imageUrl)];
            }
        }];
        TZImagePreviewController *previewVC = [[TZImagePreviewController alloc] initWithPhotos:array currentIndex:indexPath.row tzImagePickerVc:[TZImageTool imagePickerVC]];
        
        [previewVC setSetImageWithURLBlock:^(NSURL *URL, UIImageView *imageView, void (^completion)(void)) {
            [imageView sd_setImageWithURL:URL];
        }];
        
        [previewVC setDoneButtonClickBlock:^(NSArray *photos, BOOL isSelectOriginalPhoto) {
            @strongify(self);
            if (photos.count == self.dataArray.count) { // 没有改变
                return;
            }
            NSMutableArray *tempArray = [NSMutableArray array];
            [photos enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj isKindOfClass:UIImage.class]) {
                    [self.dataArray enumerateObjectsUsingBlock:^(JAddImageModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([model.imageSource isEqual:obj]) {
                            [tempArray addObject:model];
                            *stop = true;
                        }
                    }];
                } else if ([obj isKindOfClass:NSURL.class]) {
                    NSURL *finalUrl = obj;
                    [self.dataArray enumerateObjectsUsingBlock:^(JAddImageModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
                        if ([finalUrl.absoluteURL.absoluteString containsString:obj]) {
                            [tempArray addObject:model];
                            *stop = true;
                        }
                    }];
                }
            }];
            // 添加回 添加按钮
            [self.dataArray enumerateObjectsUsingBlock:^(JAddImageModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
                if (model.isAddBtn) {
                    [tempArray addObject:model];
                }
            }];
            self.dataArray = tempArray;
            [self updateSource];
        }];
        UIWindow * window = [[UIApplication sharedApplication] keyWindow];
        UIViewController *vc = [window currentTopViewController];
        [vc presentViewController:previewVC animated:true completion:nil];
        return;
    }
    //  没有删除按钮 直接删除
    if (_delActionDrowOut) {
        [LBXAlertAction showAlertWithTitle:@"温馨提示" msg:@"确定删除此照片？" chooseBlock:^(NSInteger buttonIdx) {
            if (buttonIdx == 1) {
                @strongify(self);
                [self.dataArray removeObjectAtIndex:indexPath.row];
                [self updateSource];
            }
        } buttonsStatement:@"取消",@"删除",nil];
    }else{
        self.block(-1, IntToSting(indexPath.row));
    }
}

- (void)extracted {
    [self updateSource];
}

// 添加图片
- (void)addImages:(NSArray<UIImage *> *)photos assets:(NSArray *)assets {
    __block NSMutableArray *tempArray = [NSMutableArray array];
    [photos enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        JAddImageModel *imageModel = [JAddImageModel sourceImgToImgModel:obj];
        imageModel.isAddImg = true;
        if (self.deleteImage) { // 添加删除按钮
            imageModel.deletBTControl = [ButtonControlM defaultImageName:self.deleteImage];
        }
        [tempArray addObject:imageModel];
    }];
    [self.dataArray addObjectsFromArray:tempArray];
    [self extracted];
}


- (void)updateSource {
    NSMutableArray *tempArray = [NSMutableArray array];
    [self.dataArray enumerateObjectsUsingBlock:^(JAddImageModel *model, NSUInteger idx, BOOL * _Nonnull stop) {
        if (!model.isAddBtn) {
            [tempArray addObject:model];
        }
    }];
    // [self reloadData];
    if (self.reloadFrame) {
        self.reloadFrame(-1, tempArray);
    }
}


#pragma mark -
#pragma mark 监听手势，并设置其允许移动cell和交换资源
- (void)handlelongGesture:(UILongPressGestureRecognizer *)longGesture {
    if (!_needMove) {
        return;
    }
//    if (IOS_SYSTEM_FLOAT < 9.0) {
//        //iOS9之前
//        [self action:longGesture];
//    }else{
        //iOS9及其以上版本
        [self iOS9_Action:longGesture];
//    }
}

#pragma mark item拖动 iOS9后才有
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath{
    //取出源item数据 更新
    id objc = [self.dataArray safeObjectAtIndex:indexPath.row];
    if (objc && [objc isKindOfClass:JAddImageModel.class]) {
        JAddImageModel *imgM = (JAddImageModel *)objc;
        if (imgM.isAddBtn) {
            return false;
        }
    }
    return true;
}

// MARK: - 移动中更新数据源
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath {
    //取出源item数据 更新
    id objc = [self.dataArray objectAtIndex:sourceIndexPath.item];
    //从资源数组中移除该数据
    [self.dataArray removeObject:objc];
    //将数据插入到资源数组中的目标位置上
    [self.dataArray insertObject:objc atIndex:destinationIndexPath.item];
}

- (void)iOS9_Action:(UILongPressGestureRecognizer *)longGesture{
    switch (longGesture.state) {
        case UIGestureRecognizerStateBegan:{//手势开始
            //判断手势落点位置是否在Item上
            NSIndexPath *indexPath = [self indexPathForItemAtPoint:[longGesture locationInView:self]];
            if (indexPath == nil) {
                break;
            }
            UICollectionViewCell *cell = [self cellForItemAtIndexPath:indexPath];
            [self bringSubviewToFront:cell];
            //在Item上则开始移动该Item的cell
            [self beginInteractiveMovementForItemAtIndexPath:indexPath];
        }
            break;
        case UIGestureRecognizerStateChanged:{//手势改变
            //移动过程当中随时更新cell位置
            [self updateInteractiveMovementTargetPosition:[longGesture locationInView:self]];
        }
            break;
        case UIGestureRecognizerStateEnded:{//手势结束
            {
                //移动结束后关闭cell移动
                [self endInteractiveMovement];
                [self updateSource];
            }
            
        }
            break;
        default://手势其他状态
            [self cancelInteractiveMovement];
            break;
    }
}

//========================================
//#pragma mark item拖动 iOS9之前，需要截图等操作
//static UIView *snapedView;              //截图快照
//static NSIndexPath *currentIndexPath;   //当前路径
//static NSIndexPath *oldIndexPath;       //旧路径
//
//- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)sourceIndexPath willMoveToIndexPath:(NSIndexPath *)destinationIndexPath
//{
//    //取出源item数据 更新
//    id objc = [self.dataArray objectAtIndex:sourceIndexPath.item];
//    //从资源数组中移除该数据
//    [self.dataArray removeObject:objc];
//    //将数据插入到资源数组中的目标位置上
//    [self.dataArray insertObject:objc atIndex:destinationIndexPath.item];
//
//    JAddImageModel *tempImageModel;
//    for (JAddImageModel *imageModel in self.dataArray) {
//        if (imageModel.idx == 1) {
//            tempImageModel = imageModel;
//            [self.dataArray removeObject:imageModel];
//            break;
//        }
//    }
//    if (tempImageModel) {
//
//        if (self.addLocation) {
//            [self.dataArray insertObject:tempImageModel atIndex:0];
//        }else{
//            [self.dataArray addObject:tempImageModel];
//        }
//
//        [self reloadData];
//
//    }
//}

//- (void)action:(UILongPressGestureRecognizer *)longGesture{
//    switch (longGesture.state) {
//        case UIGestureRecognizerStateBegan:{//手势开始
//            //判断手势落点位置是否在Item上
//            oldIndexPath = [self indexPathForItemAtPoint:[longGesture locationInView:self]];
//            if (oldIndexPath == nil) {
//                break;
//            }
//            UICollectionViewCell *cell = [self cellForItemAtIndexPath:oldIndexPath];
//            //使用系统截图功能，得到cell的截图视图
//            snapedView = [cell snapshotViewAfterScreenUpdates:NO];
//            snapedView.frame = cell.frame;
//            [self addSubview:snapedView];
//
//            //截图后隐藏当前cell
//            cell.hidden = YES;
//            CGPoint currentPoint = [longGesture locationInView:self];
//            [UIView animateWithDuration:0.25 animations:^{
//                snapedView.transform = CGAffineTransformMakeScale(1.2f, 1.2f);
//                snapedView.center = CGPointMake(currentPoint.x, currentPoint.y);
//            }];
//        }
//            break;
//        case UIGestureRecognizerStateChanged:{//手势改变
//            //当前手指位置 - 截图视图位置移动
//            CGPoint currentPoint = [longGesture locationInView:self];
//            snapedView.center = CGPointMake(currentPoint.x, currentPoint.y);
//
//            //计算截图视图和哪个cell相交
//            for (UICollectionViewCell *cell in [self visibleCells]) {
//                //当前隐藏的cell就不需要交换了，直接continue
//                if ([self indexPathForCell:cell] == oldIndexPath) {
//                    continue;
//                }
//                //计算中心距
//                CGFloat space = sqrtf(pow(snapedView.center.x - cell.center.x, 2) + powf(snapedView.center.y - cell.center.y, 2));
//                //如果相交一半就移动
//                if (space <= snapedView.bounds.size.width / 2) {
//                    currentIndexPath = [self indexPathForCell:cell];
//                    //移动 会调用willMoveToIndexPath方法更新数据源
//                    [self moveItemAtIndexPath:oldIndexPath toIndexPath:currentIndexPath];
//                    //设置移动后的起始indexPath
//                    oldIndexPath = currentIndexPath;
//                    break;
//                }
//            }
//        }
//            break;
//        default:{//手势结束和其他状态
//            UICollectionViewCell *cell = [self cellForItemAtIndexPath:oldIndexPath];
//            //结束动画过程中停止交互，防止出问题
//            self.userInteractionEnabled = NO;
//            //给截图视图一个动画移动到隐藏cell的新位置
//            [UIView animateWithDuration:0.25 animations:^{
//                snapedView.center = cell.center;
//                snapedView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
//            } completion:^(BOOL finished) {
//                //移除截图视图、显示隐藏的cell并开启交互
//                [snapedView removeFromSuperview];
//                cell.hidden = NO;
//                self.userInteractionEnabled = YES;
//            }];
//        }
//            break;
//    }
//}

//========================================

#pragma mark -
#pragma mark 高亮点击动画放大缩小效果
- (BOOL)collectionView:(UICollectionView *)collectionView  shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
//    if (IOS_SYSTEM_FLOAT >= 9 ) {
        return YES;
//    }else{
//        return NO;
//    }
}

//static UIView *view;
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *selectedCell = [collectionView cellForItemAtIndexPath:indexPath];
    [collectionView bringSubviewToFront:selectedCell];
    [UIView animateWithDuration:0.28 animations:^{
        selectedCell.transform = CGAffineTransformMakeScale(1.2f, 1.2f);
    }];
}

- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *selectedCell = [collectionView cellForItemAtIndexPath:indexPath];
    [UIView animateWithDuration:0.28 animations:^{
        selectedCell.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
    }];
}


@end
